package org.linitly.boot.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @author linitly
 * @date 15:09 2021/4/20
 * @description
 */
public class JsonUtils {

    private static final SerializeConfig SERIALIZE_CONFIG = new SerializeConfig();
    private static final ParserConfig PARSER_CONFIG = new ParserConfig();

    static {
        SERIALIZE_CONFIG.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
        PARSER_CONFIG.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    }

    /**
     * @param writeMapNullValue 为空的字段是否输出
     * @description 使用fastjson将对象转json时，将key由驼峰转下划线
     * 例：{aaBb: ccc}   =>    {aa_bb: ccc}
     */
	public static String humpRequestTransform(Object object, boolean writeMapNullValue) {
        return writeMapNullValue ? JSON.toJSONString(object, SERIALIZE_CONFIG, SerializerFeature.WriteMapNullValue) : JSON.toJSONString(object, SERIALIZE_CONFIG);
	}

    /**
     * @param classes 要转换的目标实体class
     * @description 使用fastjson将json转对象时，将key由下划线转驼峰
     * 例：{aaBb: ccc}   =>    {aa_bb: ccc}
     */
	public static <T> T humpResponseTransform(String json, Class<T> classes) {
        return JSON.parseObject(json, classes, PARSER_CONFIG);
    }
}
